Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
hastscript
Advanced tools
The hastscript npm package, often abbreviated as 'h', is a utility that allows for the easy creation of HAST (Hypertext Abstract Syntax Tree) nodes. HAST is a virtual DOM representation used for parsing, manipulating, and serializing HTML and XML documents. This package is particularly useful for developers working with virtual DOMs or those who need to manipulate HTML/XML documents programmatically.
Creating elements
This feature allows for the creation of HAST elements. The example demonstrates creating a 'div' element with a class of 'container' and the text 'Hello, world!' as its child.
const h = require('hastscript');
const element = h('div', {className: 'container'}, 'Hello, world!');
Creating elements with children
This feature enables the creation of HAST elements that contain other elements as children. The code sample shows how to create an unordered list ('ul') with two list items ('li') as its children.
const h = require('hastscript');
const list = h('ul', [
h('li', 'Item 1'),
h('li', 'Item 2')
]);
Creating elements with properties
This feature allows for the creation of HAST elements with specific properties. In the example, an anchor ('a') element is created with an 'href' attribute pointing to 'https://example.com' and containing the text 'Visit Example'.
const h = require('hastscript');
const link = h('a', {href: 'https://example.com'}, 'Visit Example');
Similar to hastscript, react-hyperscript provides a way to create React elements using a hyperscript-like syntax. While hastscript is focused on creating HAST nodes for HTML/XML documents, react-hyperscript is tailored for React's virtual DOM.
The virtual-dom package offers a virtual DOM implementation for efficient re-rendering of web interfaces. Unlike hastscript, which is specifically designed for creating HAST nodes, virtual-dom focuses on general virtual DOM functionality, including diffing and patching algorithms.
Snabbdom is a virtual DOM library that is lightweight and extensible. It shares similarities with hastscript in terms of manipulating virtual DOM trees but is more focused on being a core part of user interface rendering and updates, rather than specifically dealing with HAST nodes.
hast utility to create trees with ease.
This package is a hyperscript interface (like createElement
from React and
h
from Vue and such) to help with creating hast trees.
You can use this utility in your project when you generate hast syntax trees with code. It helps because it replaces most of the repetition otherwise needed in a syntax tree with function calls. It also helps as it improves the attributes you pass by turning them into the form that is required by hast.
You can instead use unist-builder
when creating any unist nodes and
xastscript
when creating xast (XML) nodes.
This package is ESM only. In Node.js (version 14.14+ or 16.0+), install with npm:
npm install hastscript
In Deno with esm.sh
:
import {h} from 'https://esm.sh/hastscript@7'
In browsers with esm.sh
:
<script type="module">
import {h} from 'https://esm.sh/hastscript@7?bundle'
</script>
import {h, s} from 'hastscript'
console.log(
h('.foo#some-id', [
h('span', 'some text'),
h('input', {type: 'text', value: 'foo'}),
h('a.alpha', {class: 'bravo charlie', download: 'download'}, [
'delta',
'echo'
])
])
)
console.log(
s('svg', {xmlns: 'http://www.w3.org/2000/svg', viewbox: '0 0 500 500'}, [
s('title', 'SVG `<circle>` element'),
s('circle', {cx: 120, cy: 120, r: 100})
])
)
Yields:
{
type: 'element',
tagName: 'div',
properties: {className: ['foo'], id: 'some-id'},
children: [
{
type: 'element',
tagName: 'span',
properties: {},
children: [{type: 'text', value: 'some text'}]
},
{
type: 'element',
tagName: 'input',
properties: {type: 'text', value: 'foo'},
children: []
},
{
type: 'element',
tagName: 'a',
properties: {className: ['alpha', 'bravo', 'charlie'], download: true},
children: [{type: 'text', value: 'delta'}, {type: 'text', value: 'echo'}]
}
]
}
{
type: 'element',
tagName: 'svg',
properties: {xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 500 500'},
children: [
{
type: 'element',
tagName: 'title',
properties: {},
children: [{type: 'text', value: 'SVG `<circle>` element'}]
},
{
type: 'element',
tagName: 'circle',
properties: {cx: 120, cy: 120, r: 100},
children: []
}
]
}
This package exports the identifiers h
and s
.
There is no default export.
The export map supports the automatic JSX runtime.
You can pass hastscript
(or hastscript/html
) or hastscript/svg
to your
build tool (TypeScript, Babel, SWC) with an importSource
option or similar.
h(selector?[, properties][, …children])
Create virtual hast trees for HTML.
h(): root
h(null[, …children]): root
h(selector[, properties][, …children]): element
selector
Simple CSS selector (string
, optional).
Can contain a tag name (foo
), IDs (#bar
), and classes (.baz
).
If the selector is a string but there is no tag name in it, h
defaults to
build a div
element, and s
to a g
element.
selector
is parsed by hast-util-parse-selector
.
When string, builds an Element
.
When nullish, builds a Root
instead.
properties
Properties of the element (Properties
, optional).
children
Children of the element (Child
or Array<Child>
, optional).
Created tree (Result
).
Element
when a selector
is passed, otherwise Root
.
s(selector?[, properties][, …children])
Create virtual hast trees for SVG.
Signatures, parameters, and return value are the same as h
above.
Importantly, the selector
and properties
parameters are interpreted as
SVG.
Child
(Lists of) children (TypeScript type).
When strings or numbers are encountered, they are turned into Text
nodes.
Root
nodes are treated as “fragments”, meaning that their children
are used instead.
type Child =
| string
| number
| null
| undefined
| Node
| Array<string | number | null | undefined | Node>
Properties
Map of properties (TypeScript type). Keys should match either the HTML attribute name, or the DOM property name, but are case-insensitive.
type Properties = Record<
string,
| string
| number
| boolean
| null
| undefined
// For comma- and space-separated values such as `className`:
| Array<string | number>
// Accepts value for `style` prop as object.
| Record<string, string | number>
>
Result
Result from a h
(or s
) call (TypeScript type).
type Result = Root | Element
The syntax tree is hast.
This package can be used with JSX.
You should use the automatic JSX runtime set to hastscript
(also available as
the more explicit name hastscript/html
) or hastscript/svg
.
👉 Note: while
h
supports dots (.
) for classes or number signs (#
) for IDs inselector
, those are not supported in JSX.
🪦 Legacy: you can also use the classic JSX runtime, but this is not recommended. To do so, import
h
(ors
) yourself and define it as the pragma (plus set the fragment tonull
).
The Use example above can then be written like so, using inline pragmas, so that SVG can be used too:
example-html.jsx
:
/** @jsxImportSource hastscript */
console.log(
<div class="foo" id="some-id">
<span>some text</span>
<input type="text" value="foo" />
<a class="alpha bravo charlie" download>
deltaecho
</a>
</div>
)
example-svg.jsx
:
/** @jsxImportSource hastscript/svg */
console.log(
<svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 500 500">
<title>SVG `<circle>` element</title>
<circle cx={120} cy={120} r={100} />
</svg>
)
This package is fully typed with TypeScript.
It exports the additional types Child
, Properties
, and Result
.
Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 14.14+ and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed.
Use of hastscript
can open you up to a cross-site scripting (XSS)
when you pass user-provided input to it because values are injected into the
syntax tree.
The following example shows how an image is injected that fails loading and therefore runs code in a browser.
const tree = h()
// Somehow someone injected these properties instead of an expected `src` and
// `alt`:
const otherProps = {src: 'x', onError: 'alert(2)'}
tree.children.push(h('img', {src: 'default.png', ...otherProps}))
Yields:
<img src="x" onerror="alert(2)">
The following example shows how code can run in a browser because someone stored an object in a database instead of the expected string.
const tree = h()
// Somehow this isn’t the expected `'wooorm'`.
const username = {
type: 'element',
tagName: 'script',
children: [{type: 'text', value: 'alert(3)'}]
}
tree.children.push(h('span.handle', username))
Yields:
<span class="handle"><script>alert(3)</script></span>
Either do not use user-provided input in hastscript
or use
hast-util-santize
.
unist-builder
— create unist treesxastscript
— create xast treeshast-to-hyperscript
— turn hast into React, Preact, Vue, etchast-util-to-html
— turn hast into HTMLhast-util-to-dom
— turn hast into DOM treesestree-util-build-jsx
— compile JSX awaySee contributing.md
in syntax-tree/.github
for
started.
See support.md
for ways to get help.
This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.
FAQs
hast utility to create trees
The npm package hastscript receives a total of 5,150,198 weekly downloads. As such, hastscript popularity was classified as popular.
We found that hastscript demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.